using System.Web;
using System.Web.SessionState;
using Kiwi.Container.Application;
using Kiwi.Container.Scope;

namespace Kiwi.Container.Web
{
    public interface IHttpSessionContainerActivator : ILocalContainerActivator
    {
    }

    public class HttpSessionContainerActivator : IHttpSessionContainerActivator
    {
        private const string SessionItemKey = "HttpSessionContainerActivator.Container";
        public static readonly ILocalContainerActivator Default = new HttpSessionContainerActivator();

        #region IHttpSessionContainerActivator Members

        public IContainer GetLocalContainer(IContainer parentContainer)
        {
            var context = HttpContext.Current;
            if (context == null)
            {
                return null;
            }
            var session = context.Session;
            if (session == null)
            {
                return null;
            }

            var container = GetSessionContainer(session);
            if (container != null)
            {
                return container;
            }

            container = parentContainer.CreateContainer(ContainerScope.HttpSession);
            SetSessionContainer(session, container);

            return container;
        }

        #endregion

        private static IContainer GetSessionContainer(HttpSessionState session)
        {
            return session[SessionItemKey] as IContainer;
        }

        private static void SetSessionContainer(HttpSessionState session, IContainer container)
        {
            session[SessionItemKey] = container;
        }

        public static void ReleaseSessionContainer(HttpSessionState session)
        {
            var container = GetSessionContainer(session);
            if (container != null)
            {
                SetSessionContainer(session, null);
                container.Dispose();
            }
        }
    }
}